import axios from 'axios';
import md5 from 'js-md5';

const appkey = 'C5F7515E43E04E35853A0F910740AA43';
const secret = 'E9A3179D993A4033AC649BEF1DFD4ECD';
const baiduak = '7OcadXOGwN9QYFOuuABRmXj6AYhm51Rk';
    var baseApiURL = 'http://fangcun.ngrok.iiocode.com';  //大总
    //var baseApiURL = 'http://192.168.0.235:8003';

var uploadsrc = baseApiURL + '/sys/v1.0/qiniu/upload/image';

var BaiduMapAk = baiduak; 

const nonce = Math.random() * 1000000;
const timestamp = new Date().getTime();
const signature = md5(md5(md5(appkey + nonce + secret + timestamp))).toUpperCase();

const security_token = localStorage.getItem('security_token') != null ? localStorage.getItem('security_token') : '';
const defaults = {
    baseURL: baseApiURL,
    timeout: 60000,
    withCredentials: true,
    headers: {
        'signature': signature,
        'nonce': nonce,
        'timestamp': timestamp,
        'appkey': appkey,
        'token': security_token
    }
};

//axios 默认参数设置
Object.assign(axios.defaults, defaults);

export function dynamicHeader() {
    // 发送请求之前处理数据
    const nonce = Math.random() * 1000000;
    const timestamp = new Date().getTime();
    const signature = md5(md5(md5(appkey + nonce + secret + timestamp))).toUpperCase();
    const security_token = localStorage.getItem('security_token') != null ? localStorage.getItem('security_token') : '';
    var dHeader = {
        'signature': signature, 'nonce': nonce, 'timestamp': timestamp, 'appkey': appkey, 'token': security_token
    };
    return dHeader;
}

//请求拦截器
axios.interceptors.request.use(function(config) {
    config.data = config.data ? config.data : {};
    config.headers = dynamicHeader();
    return config;
}, function(error) {
    //请求错误进行处理
    return Promise.reject(error);
});

axios.interceptors.response.use(function(response) {
    if (response.headers['token'] != null && response.headers['token'] != '') {
        localStorage.setItem('security_token', response.headers['token']);
    }
    if (response.data.returnCode == '20013') {
        alert('无权访问');
    }
    // 配置请求回来的信息
    if (response.data.returnCode == '20003' || response.data.returnCode == '20004' || response.data.returnCode == '20005') {
        alert('您的登录已过期，请重新登录');
        clearCookie();
        window.top.location = '/#/login';
    }

    return response.data;
}, function(error) {
    return Promise.reject(error);
});


function clearCookie() {
    localStorage.removeItem('ms_username');
    localStorage.removeItem('security_token');
}

/*接口文档*/
import * as apiInfo from '../api/api.js';

Object.keys(apiInfo).forEach(key => {
    window[key] = apiInfo[key];
});
export { uploadsrc,BaiduMapAk };
